package com.youfang.sixthmedia.controller;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.commons.io.FileUtils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
import android.widget.ListView;
import ch.boye.httpclientandroidlib.HttpResponse;
import ch.boye.httpclientandroidlib.client.HttpClient;
import ch.boye.httpclientandroidlib.client.methods.HttpGet;
import ch.boye.httpclientandroidlib.util.EntityUtils;

import com.gzit.adapter.CustomerListAdapter;
import com.gzit.utils.StringUtils;
import com.youfang.sixthmedia.common.YoufangContext;
import com.youfang.sixthmedia.net.HttpRemoter;

//网友头像控制器
public class HeaderController extends Thread {

	private static final String TAG = "HeaderController";

	private BlockingQueue<Header> downloadQueue = new LinkedBlockingQueue<Header>();

	private ListView listview;
	private HeaderAdapter<? extends Header> adapter;

	private boolean running = true;

	// ///////////////////////////////////////////////////////////////////////////
	public static abstract class Header implements Serializable {
		public int userid;
		public String logo;
		public transient Bitmap logoBitmap;

	}

	public abstract static class HeaderAdapter<T> extends
			CustomerListAdapter<T> {
		public HeaderAdapter(Context context, int itemLayoutId) {
			super(context, itemLayoutId);
		}
	}

	// ///////////////////////////////////////////////////////////////////////////

	// ///////////Cache部分//////////////
	public static class Cache {
		public static String cachePath = YoufangContext.APP_DIR + "header"
				+ File.separator;

		static {
			ensureCachePath();
		}

		private static void ensureCachePath() {
			File file = new File(cachePath);
			if (!file.exists()) {
				file.mkdirs();
			}
		}

		public static void clearCache() throws IOException {
			FileUtils.cleanDirectory(new File(cachePath));
		}

		public static Bitmap getFromCache(Header b) throws Exception {
			String logo = cachePath + b.userid;
			File logoFile = new File(logo);
			if (!logoFile.exists()) {
				return null;
			}
			return BitmapFactory.decodeFile(logo);

		}

		public static Uri getFromCache(int userid) {
			if (userid == 0) {
				return null;
			}

			String logo = cachePath + userid;
			File logoFile = new File(logo);
			if (!logoFile.exists()) {
				return null;
			}
			return Uri.fromFile(logoFile);

		}

		// 将logo数据保存到缓存目录下
		private static void cache(Header b, byte[] resultBytes)
				throws Exception {
			File logoFile = new File(cachePath + b.userid);
			FileUtils.writeByteArrayToFile(logoFile, resultBytes);
		}

	}

	// /////////////////////////////////////////////////

	public HeaderController() {
		this.setName(TAG);
		this.start();

	}

	public void setup(ListView listview, HeaderAdapter<? extends Header> adapter) {
		this.listview = listview;
		this.adapter = adapter;
	}

	// 在刷新时候调用
	public void onRefresh(List<? extends Header> headers) {
		Log.i(TAG, TAG + " onRefresh!");
		this.downloadQueue.clear();
		this.onMore(headers);
	}

	// 在点击加载更多的时候调用
	public void onMore(List<? extends Header> headers) {
		for (Header b : headers) {

			// LOGO已经存在或者logo的地址不存在，则不放入下载队列
			if (b.logoBitmap != null || StringUtils.isStickBlank(b.logo)) {
				continue;
			}

			// 没取到过logo头像则放入下载队列
			downloadQueue.offer(b);
		}

	}

	// 在activity停止的时候调用该方法停止logo的处理
	public void onStop() {

		Log.i(TAG, TAG + " OnStop!");
		this.running = false;
		this.interrupt();
		this.downloadQueue.clear();

	}

	// 主线程体
	public void run() {
		while (running) {
			Header b;
			try {
				b = downloadQueue.take();
				doDownload(b);
				if (this.isInterrupted()) {
					return;
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
				running = false;
			}

		}

		Log.i(TAG, TAG + " Thread stopped!");

	}

	// 通知图标已就绪
	private void notifyLogoReady(Header b) {

		final int begin = this.listview.getFirstVisiblePosition();
		int end = this.listview.getLastVisiblePosition();

		for (int i = begin; i <= end; i++) {

			Object item = this.listview.getItemAtPosition(i);
			if (item == null) {
				continue;
			}

			if (b.userid == (((Header) item).userid)) {

				this.listview.post(new Runnable() {

					@Override
					public void run() {
						adapter.notifyDataSetChanged();
						listview.setSelection(begin);

					}
				});

			}

		}

	}

	private void doDownload(Header header) {

		HttpClient client = HttpRemoter.getYoufangRemoter().getHttpClient();
		try {

			URI logoURI = new URI(header.logo);
			HttpGet get = new HttpGet(logoURI);
			HttpResponse resp = client.execute(get);
			int statusCode = resp.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				Log.d(TAG, TAG + " download failed!statuscode:" + statusCode
						+ ":" + header.logo);
				return;
			}

			byte[] resultBytes = EntityUtils.toByteArray(resp.getEntity());
			Bitmap bitmap = BitmapFactory.decodeByteArray(resultBytes, 0,
					resultBytes.length);
			header.logoBitmap = bitmap;

			// 缓存图标
			Cache.cache(header, resultBytes);

			// 通知logo已下载
			notifyLogoReady(header);

			Log.d(TAG, TAG + " download ok:" + header.logo);

		} catch (Exception e) {
			e.printStackTrace();
			Log.d(TAG,
					TAG + " download failed:" + header.logo + "message:"
							+ e.getMessage());

			return;

		}

	}

	public void onDestroy() {
		Log.i(TAG, TAG + " onDestroy!");

	}

}
